package org.hq.web.utils;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.data.redis.serializer.RedisSerializer;

import java.util.HashSet;
import java.util.Set;

@SpringBootTest
class RedisUtilTest {
    @Autowired
    private RedisTemplate<Object, Object> redis;
    @Autowired
    private RedisTemplate<String, Object> myredis;

    @Test
    void setRedis() {
        String key = "/html/202402/82755.htmlttt";
        myredis.opsForValue().set(key,1813033378);
        Object mykey = myredis.opsForValue().get(key);
        System.out.println("key:    " + mykey);
    }


    @Test
    void opsForValue() {
        String key = "myqq";
        redis.opsForValue().set(key,1813033378);
        Object mykey = redis.opsForValue().get(key);
        System.out.println("key:    " + mykey);
    }
    @Test
    void deletekey() {
   redis.delete("lian");

    }
    @Test
    public void clearAllDatabases() {
       //清空数据库
        redis.getConnectionFactory().getConnection().flushAll();
    }
    @Test
    void newredis() {
        //设置 redis key 字符串
        redis.setKeySerializer(RedisSerializer.string());
        //设置 redis hash key 字符串
        redis.setHashKeySerializer(RedisSerializer.string());
        //设置 redis Value 为 json 数据
        redis.setValueSerializer(RedisSerializer.json());
        //设置 redis hash Value 为 json 数据
        redis.setHashValueSerializer(RedisSerializer.json());
        String key = "/html/202402/82755.html";
        String mykey = (String) redis.opsForValue().get(key);
        System.out.println("key:    " + mykey);
    }






    @Test
    void getkey() {
        Set<String> keys = new HashSet<>();
        ScanOptions options = ScanOptions.scanOptions().match("*").build();
        try (Cursor<byte[]> cursor = redis.getConnectionFactory().getConnection().scan(options)) {
            while (cursor.hasNext()) {
                keys.add(new String(cursor.next()));
            }
        }
        for (String key : keys) {
            redis.delete(key);
        }
    }
}